package com.googlecode.horncomb.web.spring.tags;

import javax.servlet.jsp.JspException;

import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.tags.form.LabelTag;
import org.springframework.web.servlet.tags.form.TagWriter;

import com.googlecode.horncomb.web.util.TagUtils;

public class SecurityLabelTag extends LabelTag {
	private static final long serialVersionUID = -8441739627467717501L;
	private static final Double defaultPermission = 9999d;
	private String permission = null;
	private String required = "false";

	/**
	 * Writes the opening '<code>label</code>' tag and forces a block tag so
	 * that body content is written correctly.
	 * @return {@link javax.servlet.jsp.tagext.Tag#EVAL_BODY_INCLUDE}
	 */
	protected int writeTagContent(TagWriter tagWriter) throws JspException {
		double pms = this.getPermission();
		if (pms < 0) {
			return EVAL_PAGE;
		}
		super.writeTagContent(tagWriter);
		// 输出红色*号标识必填
		if (pms>0 && this.getRequired()) {
			tagWriter.startTag("font");
			tagWriter.writeAttribute("color", "red");
			tagWriter.appendValue("*");
			tagWriter.endTag();
		}
		return EVAL_BODY_INCLUDE;
	}

	@Override
	public int doEndTag() throws JspException {
		if (this.getPermission() < 0) {
			return EVAL_PAGE;
		}
		return super.doEndTag();
	}

	@Override
	protected String resolveCssClass() throws JspException {
		if (StringUtils.hasText(this.getPath()) && getBindStatus().isError()
				&& StringUtils.hasText(getCssErrorClass())) {
			return ObjectUtils.getDisplayString(evaluate("cssErrorClass",
					getCssErrorClass()));
		} else {
			return ObjectUtils.getDisplayString(evaluate("cssClass",
					getCssClass()));
		}
	}

	/**
	 * @param permission
	 *            the permission to set
	 */
	public void setPermission(String permission) throws NumberFormatException,
			JspException {
		this.permission = permission;
	}

	/**
	 * @return
	 * @throws NumberFormatException
	 * @throws JspException
	 */
	protected Double getPermission() throws NumberFormatException, JspException {
		String pms = this.getDisplayString(this.evaluate("permission",
				this.permission));
		if (!StringUtils.hasText(pms)) {
			Object pagePrmsObj = this.pageContext
					.getAttribute(SecurityInputTag.PAGE_PERMISSION_KEY);
			if (pagePrmsObj != null) {
				pms = pagePrmsObj.toString();
			}
		}
		if (!StringUtils.hasText(pms)) {
			return defaultPermission;
		} else {
			return Double.parseDouble(pms);
		}
	}

	/**
	 * @param required
	 *            the required to set
	 */
	public void setRequired(String required) {
		this.required = required;
	}

	protected boolean getRequired() throws JspException {
		return TagUtils.getBooleanValue("required", this.required, pageContext);
	}
}
